#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include "common.h"
#include "network.h"
#include "user_auth.h"
#include "online_list.h"

int main() {
    int ret;
    pthread_t recv_thread;
    struct online_user* online_list = NULL;
    int socket_fd;
    int is_running = 1;

    printf("===== 聊天室客户端 =====\n");

    if ((socket_fd = connect_to_server()) < 0) {
        return -1;
    }

    printf("成功连接到服务器 %s:%d\n", SERVER_IP, SERVER_PORT);

    int op = 0;
    int login_success = 0;

    while (!login_success) {
        printf("请选择操作: 1.注册, 2.登录, 3.退出\n");
        if (scanf("%d", &op) != 1) {
            printf("无效输入\n");
            while (getchar() != '\n');
            continue;
        }
        while (getchar() != '\n');

        switch (op) {
            case 1:
                register_user(socket_fd);
                break;
            case 2:
                if (login_user(socket_fd) == 0) {
                    login_success = 1;
                    send(socket_fd, "LIST", 4, 0);
                }
                break;
            case 3:
                close(socket_fd);
                return 0;
            default:
                printf("无效选择\n");
        }
    }

    struct thread_args* args = malloc(sizeof(struct thread_args));
    if (!args) {
        perror("内存分配失败");
        close(socket_fd);
        return -1;
    }
    args->socket_fd = socket_fd;
    args->is_running = &is_running;
    args->online_list = &online_list;

    if (pthread_create(&recv_thread, NULL, recv_thread_func, args) != 0) {
        perror("无法创建接收线程");
        free(args);
        close(socket_fd);
        return -1;
    }

    write_message(socket_fd, online_list);
    is_running = 0;

    printf("\n正在退出...\n");
    close(socket_fd);
    pthread_join(recv_thread, NULL);
    free_online_users(online_list);

    printf("已退出聊天室\n");
    return 0;
}